home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16751 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: svnews.ubinet.ubs.com!ubszh!ian.johnston@ubs.com
  2. From: ian.johnston@ubs.com (Ian Johnston (by ubsswop))
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Creating an object via new with ONLY a pointer to the object
  5. Date: 12 Apr 1996 07:20:25 GMT
  6. Organization: UBS
  7. Distribution: world
  8. Message-ID: <4kl07p$bpm@ubszh.fh.zh.ubs.com>
  9. References: <4kh07v$lno@crchh327.rich.bnr.ca> <316D04B3.41C6@meca.polymtl.ca>
  10. NNTP-Posting-Host: nol2179.fh.zh.ubs.com
  11.  
  12. In article <316D04B3.41C6@meca.polymtl.ca>, Pierre Ferland <pierre@meca.polymtl.ca> writes:
  13. |> Bret Bieghler wrote:
  14.  
  15. [On creating instances of derived classes, given a key, such as a class name]
  16.  
  17. |> What you need is a virtual constructor, that is a pure virtual 
  18. |> function declared in the base class:
  19. |> 
  20. |> class CommandObject_c {
  21. |> 
  22. |>     public:
  23. |>         virtual CommandObject_c *VirtualConstruct(void)=0;
  24. |> 
  25. |> };
  26. |> 
  27. |>   class ExitCommand_c {
  28. |>     public:
  29. |>         // Copy constructor, needed in virtual constructor
  30. |>         ExitCommand_c(ExitCommand_c&);
  31. |> 
  32. |>         // virtual constructor 
  33. |>         CommandObject_c *VirtualConstruct(void) {
  34. |>             return new ExitCommand_c(*this);
  35. |>         }        
  36. |>   };
  37. |> and implemented in the derived classes:
  38. |> 
  39. |>   class ExitCommand_c {
  40. |>     public:
  41. |>         // Copy constructor, needed in virtual constructor
  42. |>         ExitCommand_c(ExitCommand_c&);
  43. |> 
  44. |>         // virtual constructor 
  45. |>         CommandObject_c *VirtualConstruct(void) {
  46. |>             return new ExitCommand_c(*this);
  47. |>         }        
  48. |>   };
  49. |> 
  50. |> When you handle a pointer
  51. |> to a base class object (thus using polymorphisms), the only entity
  52. |> that can realize the cloning operation is the derived object itself,
  53. |> since he's the only one to know ``what he is''.
  54. |> The only counterpart in that is that if you design very
  55. |> complicated (avoid) class family trees with multiple inheritence,
  56. |> there might be ambiguities.  In such a case, my advice is
  57. |> to re-design the families and use containers and interfaces
  58. |> to simplify the class diagram.  Some other approaches can
  59. |> lead to ugly situations!
  60.  
  61. This won't work. You would need an instance of ExitCommand on which to
  62. call the VirtualConstruct() function.
  63.  
  64. But the whole point is how to create an instance of ExitCommand in the
  65. first place!
  66.  
  67. Ian
  68.